<?php

namespace app\models;

/**
 * 后台管理员
 * Class Manager
 * @package app\models
 */
class Manager
{
    const SessionKey = 'session_key_manager';

    /**
     * 获取当前登录用户(如果为null,则未登录)
     * @return mixed|null
     */
    public static function getCurrentManager()
    {
        if (\Yii::$app->session->has(self::SessionKey)) {
            $manager = \Yii::$app->session->get(self::SessionKey);
            $manager['is_department_admin'] = Department::isDepartmentManager($manager['id']);
            $department = Department::getDepartmentByManagerId($manager['id']);
            $manager['department'] = $department;


            return $manager;
        }

//        if (YII_ENV == 'dev') {
//            //调试用---begin
//            $currentManager = self::validatePassword('admin', '1');
//            self::setCurrentManager($currentManager);
//            return $currentManager;
//            //-----end
//        }

        return null;
    }

    /**
     * 用户登录以后,设置到session中
     * @param $manager
     */
    public static function setCurrentManager($manager)
    {
        \Yii::$app->session->remove(self::SessionKey);
        \Yii::$app->session->set(self::SessionKey, $manager);
    }

    /**
     * 用户登录验证
     * @param $account
     * @param string $password md5加密
     * @return array|false|null
     */
    public static function validatePassword($account, $password)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT * FROM v_manager WHERE account=:account AND `password`=:password AND is_enabled=1');
        $cmd->bindValue(':account', $account);
        $cmd->bindValue(':password', md5($password));
        $item = $cmd->queryOne();
        if ($item == false) {
            $item = null;
        } else {
            $cmd = \Yii::$app->db->createCommand('
                SELECT t3.* FROM t_manager_role t0
                LEFT JOIN t_role t1 ON t1.id=t0.role_id
                LEFT JOIN t_role_function_point t2 ON t2.role_id=t1.id
                LEFT JOIN t_function_point t3 ON t3.id=t2.function_point_id
                WHERE t1.is_enabled=1 AND t0.manager_id=:managerId');
            $cmd->bindValue(':managerId', $item['id']);
            $item['permission'] = $cmd->queryAll();
        }
        return $item;
    }

    /**
     * 退出登录
     */
    public static function logout()
    {
        \Yii::$app->session->removeAll();
    }

    /**
     * 获取系统所有管理员总数(主要用于分页)
     * @return false|null|string
     */
    public static function getCount()
    {
        $cmd = \Yii::$app->db->createCommand('SELECT COUNT(1) FROM v_manager');
        $count = $cmd->queryScalar();
        return $count;
    }

    /**
     * 获取系统机构及下级机构管理员总数(主要用于分页)
     * @return false|null|string
     */
    public static function getSelfChildrenCount($institutionCode)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT COUNT(t0.id) FROM v_manager t0 INNER JOIN t_institution  t1
        on t1.code = t0.institution_code and (t1.code=:institutionCode or t1.parent_code=:institutionCode)
        where t1.is_enabled = 1 ');
        $cmd->bindValue(':institutionCode', $institutionCode);
        $count = $cmd->queryScalar();
        return $count;
    }

    /**
     * 获取管理员列表
     * @param int $offset 分页查询起始位置
     * @param int $limit 分页查询每页数量
     * @return array
     */
    public static function getList($offset, $limit)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT * FROM v_manager ORDER BY create_datetime DESC LIMIT :offset, :limit');
        $cmd->bindValue(':offset', $offset);
        $cmd->bindValue(':limit', $limit);

        $items = $cmd->queryAll();

        return $items;
    }

    /**
     * 获取机构及下级机构管理员列表
     * @param int $offset 分页查询起始位置
     * @param int $limit 分页查询每页数量
     * @return array
     */
    public static function getSelfChildrenList($institutionCode, $offset, $limit)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT t0.* FROM v_manager t0 INNER JOIN t_institution  t1
        on t1.code = t0.institution_code and (t1.code=:institutionCode or t1.parent_code=:institutionCode) and t1.is_enabled = 1
        ORDER BY t0.create_datetime DESC LIMIT :offset, :limit');
        $cmd->bindValue(':institutionCode', $institutionCode);
        $cmd->bindValue(':offset', $offset);
        $cmd->bindValue(':limit', $limit);

        $items = $cmd->queryAll();

        return $items;
    }

    /**
     * 获取某机构下所有管理员的数量
     * @param $institutionCode
     * @return false|null|string
     */
    public static function getCountByInstitution($institutionCode)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT COUNT(1) FROM v_manager WHERE institution_code=:institutionCode');
        $cmd->bindValue(':institutionCode', $institutionCode);
        $count = $cmd->queryScalar();
        return $count;
    }

    /**
     * 获取某机构下管理员列表
     * @param string $institutionCode
     * @param int $page 从1页开始
     * @param int $pageSize
     * @return array
     */
    public static function getListByInstitution($institutionCode, $offset, $limit)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT * FROM v_manager WHERE institution_code=:institutionCode LIMIT :offset, :limit');
        $cmd->bindValue(':institutionCode', $institutionCode);
        $cmd->bindValue(':offset', $offset);
        $cmd->bindValue(':limit', $limit);

        $items = $cmd->queryAll();
        return $items;
    }

    /**
     * 获取管理员详情(包含管理员角色)
     * @param $managerId
     * @return array|false
     */
    public static function getDetail($managerId)
    {
        $cmd = \Yii::$app->db->createCommand('SELECT * FROM v_manager WHERE id=:managerId');
        $cmd->bindValue(':managerId', $managerId);
        $item = $cmd->queryOne();
        if (isset($item)) {
            $cmd = \Yii::$app->db->createCommand('SELECT role_id FROM t_manager_role WHERE manager_id=:managerId');
            $cmd->bindValue(':managerId', $managerId);
            $item['role_list'] = $cmd->queryColumn();
        }

        return $item;
    }

    /**
     * 判断是否存在该管理员
     * @param $phone
     * @return array|false|null
     */
    public static function existManager($phone)
    {
        $sql = 'SELECT t1.id AS record_id,t1.contacter_phone,t2.account,t2.institution_code
                FROM t_apply_for_institution_record t1 
                INNER JOIN t_manager t2 ON t2.account = t1.contacter_phone
                WHERE t1.contacter_phone = :phone';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':phone', $phone);
        $result = $cmd->queryOne();
        if (!$result) {
            return null;
        }
        return $result;
    }

    /**
     * 添加管理员
     * @param $manager
     * @return int
     * @throws \yii\db\Exception
     */
    public static function add($manager)
    {

        $result = 0;
        $connection = \Yii::$app->db;
        $transaction = $connection->beginTransaction();
        try {
            //判断是否有重复account
            $sql = 'SELECT count(1) FROM t_manager WHERE account = :account';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':account', $manager['account']);
            $result = $cmd->queryScalar();
            if ($result == '1') {
                $transaction->rollBack();
                return false;
            }

            $cmd = \Yii::$app->db->createCommand('call p_add_manager(:in_institution_code, :in_name, :in_account, :in_password, :in_phone, :in_is_enabled, :in_remark)');
            $cmd->bindValue(':in_institution_code', $manager['institution_code']);
            $cmd->bindValue(':in_name', $manager['name']);
            $cmd->bindValue(':in_account', $manager['account']);
            $cmd->bindValue(':in_password', md5($manager['password']));
            $cmd->bindValue(':in_phone', $manager['phone']);
            $cmd->bindValue(':in_is_enabled', $manager['is_enabled']);
            $cmd->bindValue(':in_remark', $manager['remark']);
            $id = $cmd->queryScalar();

            if (isset($manager['role_list'])) {
                foreach ($manager['role_list'] as $role) {
                    $cmd = \Yii::$app->db->createCommand('call p_add_manager_role(:in_manager_id, :in_role_id)');
                    $cmd->bindValue(':in_manager_id', $id);
                    $cmd->bindValue(':in_role_id', $role);
                    $cmd->execute();
                }
            }

            //判断是否有部门，有部门的插入部门管理员表
            if (isset($manager['department_id']) && $manager['department_id'] <> '') {
                $sql = 'INSERT INTO t_department_manager(department_id,manager_id)
                    VALUES (:department_id,:manager_id)';

                $cmd = \Yii::$app->db->createCommand($sql);
                $cmd->bindValue(':department_id', $manager['department_id']);
                $cmd->bindValue(':manager_id', $id);
                $cmd->execute();
            }

            $transaction->commit();
            $result = 1;
        } catch (\Exception $e) {
            $result = 0;
            $transaction->rollBack();
        }

        return $result;
    }

    /**
     * 修改管理员
     * @param $manager
     * @return int
     * @throws \yii\db\Exception
     */
    public static function modify($manager)
    {
        $result = 0;
        $connection = \Yii::$app->db;
        $transaction = $connection->beginTransaction();
        try {
            $cmd = \Yii::$app->db->createCommand('call p_modify_manager(:in_id, :in_institution_code, :in_name, :in_account, :in_phone, :in_is_enabled, :in_remark)');
            $cmd->bindValue(':in_id', $manager['id']);
            $cmd->bindValue(':in_institution_code', $manager['institution_code']);
            $cmd->bindValue(':in_name', $manager['name']);
            $cmd->bindValue(':in_account', $manager['account']);
            $cmd->bindValue(':in_phone', $manager['phone']);
            $cmd->bindValue(':in_is_enabled', $manager['is_enabled']);
            $cmd->bindValue(':in_remark', $manager['remark']);
            $id = $cmd->queryScalar();
            $result++;

            $cmd = \Yii::$app->db->createCommand('call p_delete_manager_role(:in_manager_id)');
            $cmd->bindValue(':in_manager_id', $manager['id']);
            $result += $cmd->execute();

            if (isset($manager['role_list'])) {
                foreach ($manager['role_list'] as $role) {
                    $cmd = \Yii::$app->db->createCommand('call p_add_manager_role(:in_manager_id, :in_role_id)');
                    $cmd->bindValue(':in_manager_id', $id);
                    $cmd->bindValue(':in_role_id', $role);
                    $result += $cmd->execute();
                }
            }

            if (isset($manager['department_id'])) {
                //修改管理员部门
                $sql = 'DELETE FROM t_department_manager WHERE manager_id = :manager_id';
                $cmd = \Yii::$app->db->createCommand($sql);
                $cmd->bindValue(':manager_id', $manager['id']);
                $cmd->execute();

                if ($manager['department_id'] <> '') {
                    $sql = 'INSERT INTO t_department_manager(department_id,manager_id)
                    VALUES (:department_id,:manager_id)';
                    $cmd = \Yii::$app->db->createCommand($sql);
                    $cmd->bindValue(':department_id', $manager['department_id']);
                    $cmd->bindValue(':manager_id', $manager['id']);
                    $cmd->execute();
                }
            }
            $transaction->commit();
        } catch (\Exception $e) {
            $result = 0;
            $transaction->rollBack();
        }

        return $result;
    }

    /**
     * 修改登陆人员信息
     * @param $manager
     * @return int
     * @throws \yii\db\Exception
     */
    public static function modifyInfo($manager)
    {
        //$cmd = \Yii::$app->db->createCommand('call p_modify_person_info(:in_id, :in_institution_code, :in_name, :in_account, :in_phone, :in_is_enabled, :in_remark)');
        $cmd = \Yii::$app->db->createCommand('call p_modify_person_info(:in_id, :in_name, :in_phone, :in_remark)');
        $cmd->bindValue(':in_id', $manager['id']);
        // $cmd->bindValue(':in_institution_code', $manager['institution_code']);//过程内不使用
        $cmd->bindValue(':in_name', $manager['name']);
        //$cmd->bindValue(':in_account', $manager['account']);//过程内不使用
        $cmd->bindValue(':in_phone', $manager['phone']);
        //$cmd->bindValue(':in_is_enabled', $manager['is_enabled']);//过程内不使用
        $cmd->bindValue(':in_remark', $manager['remark']);
        $result = $cmd->queryScalar();

        return $result;
    }

    /**
     * 修改密码
     */
    public static function modifyPassword($id, $password)
    {
        $sql = "call p_modify_password(:in_id,:in_password)";
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(":in_id", $id);
        $cmd->bindValue(":in_password", md5($password));
        $result = $cmd->queryScalar();

        return $result;
    }

    public static function checkManagerAccountIsRepeat($account)
    {
        $filterSQL = '';

//        //添加查询条件
//        if ($managerId != null && $managerId != '') {
//            $filterSQL = $filterSQL . " and t.id !=:id ";
//        }

        //查询SQL
        $sql = 'select t.* from t_manager t where t.account =:account';
        //创建查询
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':account', $account);
//        //绑定参数
//        if ($managerId != null && $managerId != '') {
//            $cmd->bindValue(':id', $managerId);
//        }
        //执行获取结果
        $result = $cmd->queryAll();

        if ($result != null && $result != '' && count($result) > 0) {
            return 1;
        } else {
            return 0;
        }

    }

}